<?php
namespace app\api\controller\vppz;


use think\Cache;


use \app\admin\model\vppz\Coupon as CouponModel;
use \app\admin\model\vppz\Hospital as HospitalModel;
use \app\admin\model\vppz\UseCoupon as UseCouponModel;
use fast\Random;

use \addons\vppz\library\Vpower;

class Coupon extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->CouponModel = new CouponModel;
        $this->HospitalModel = new HospitalModel;
        $this->UseCouponModel = new UseCouponModel;
    }


    /**
     * 服务下单页
     */
    public function lists(){
		$area=$this->_area;
		$mine = $this->_mine;
        $coupon = $this->CouponModel->order('weigh','DESC')->select();
        if(empty($bjjy) === FALSE){
            foreach ($coupon as $bk=>$bj){
                $coupon[$bk]['createtime'] = date('Y-m-d H:i:s',$coupon[$bk]['createtime']);
            }
        }
		$this->success('',array(
			'now'=>time(),
			'coupon'=>$coupon
		));
    }

    /**
     * 领优惠券
     * @return void
     */
    public function getcoupon(){
        $hospitalid = input('id');
        $mine = $this->_mine;
        //判断是否有领过未使用的优惠券
        $has_coupon = $this->UseCouponModel->where(array(
            'uid'   => $mine['id'],
            'status'=>1,
            'hospitalid'=>$hospitalid
        ))->where('expiretime','>',time())->column('cid');
        $coupon = $this->CouponModel->where('hospitalid','=',$hospitalid)->whereNull('deletetime')->column('id');
        $now_coupon = array_diff($coupon,$has_coupon);
        if (empty($coupon)){
            $this->error('该医院未创建优惠券，请联系医院确认');
        }
        if(empty($now_coupon)){
            $this->error('您有未核销的优惠券，请先进行核销操作');
        }
        if(empty($now_coupon) === FALSE){
            foreach ($now_coupon as $k=>$v){
                $data = array(
                    'uid'   => $mine['id'],
                    'cid'   => $v,
                    'hospitalid'   => $hospitalid,
                    'expiretime'=>time()+365*86400,
                    'createtime'=>time(),
                    'status'=>1,
                    'code'=>$mine['id'].$k.\Tools::generateShortUniqueId(),
                    'updatetime'=>time()
                );
                $this->UseCouponModel->insert($data);
            }
        }
        $this->success();
    }

    /**
     * 核销
     * @return void
     */
    public function usecoupon(){
        $id = input('id');
        $mine = $this->_mine;
        $data = array(
            'status'=>2,
            'updatetime'=>time()
        );
        $this->UseCouponModel->where('id','=',$id)->update($data);
        $this->success();
    }
    //领取记录
    public function mylists(){
		$area=$this->_area;
		$mine = $this->_mine;
        $status = input('status',1);
        $coupon = $this->UseCouponModel
            ->where(['uid'=>$mine['id'],'status'=>$status])
            ->order('createtime','DESC')
            ->select();
        $res = [];
        if(empty($coupon) === FALSE){
            foreach ($coupon as $bk=>$bj){
                $coupon[$bk]['createtime'] = date('Y-m-d H:i:s',$bj['createtime']);
                $getStatusList = $this->UseCouponModel->getStatusList();
                foreach ($getStatusList as $k=>$status){
                    if($k == $bj['status']){
                        $bj['status_text'] = $status;
                    }
                }
                //获取优惠券信息
                $detail = $this->CouponModel->find($bj['cid']);
                if(empty($detail)) continue;
                $bj['name'] = $detail['name']??'系统优惠券';
                $bj['bgImage'] = \addons\vppz\library\Vpower::dourl($detail['image']);
                $bj['logo'] = \addons\vppz\library\Vpower::dourl('/uploads/20250418/0d809c617be0cae1dbc5588d6a147e1a.png');
                $bj['limit'] = $detail['limit'];
                if($detail['type'] == 1){
                    $bj['amount'] = $detail['amount'];
                }else{
                    $bj['amount'] = $detail['amount'] * 100;
                }
                $bj['coupon_type'] = $detail['type'];
                $hospital = $this->HospitalModel->find($detail['hospitalid']);
                if(empty($hospital))continue;
                $bj['hospitalName'] = $hospital['name'];
                $res[] = $bj;
            }
        }
		$this->success('',array(
			'now'=>time(),
			'coupon'=>$res
		));
    }
    //核销历史
    public function hexiaohistory(){
        $hospitalid = input('hospitalId','');
        if(empty($hospitalid)){
            $this->error('参数有误');
            return false;
        }
        $pageNum = input('pageNum',1);
        $pageSize = input('pageSize',10);
        $coupon = $this->UseCouponModel
            ->where(['status'=>2,'hospitalid'=>$hospitalid])
            ->order('updatetime','DESC')->limit(($pageNum-1)*$pageSize,$pageSize)
            ->select();
        $total = $this->UseCouponModel
            ->where(['status'=>2,'hospitalid'=>$hospitalid])->count();
        $res = [];
        if(empty($coupon) === FALSE){
            foreach ($coupon as $bk=>$bj){
                $coupon[$bk]['createtime'] = date('Y-m-d H:i:s',$bj['createtime']);
                $coupon[$bk]['updatetime'] = date('Y-m-d H:i:s',$bj['hexiaotime']);

                //获取优惠券信息
                $detail = $this->CouponModel->find($bj['cid']);
                if(empty($detail)) continue;
                $bj['name'] = $detail['name']??'系统优惠券';
                $bj['coupon_type'] = $detail['type'];
                $hospital = $this->HospitalModel->find($detail['hospitalid']);
                if(empty($hospital))continue;
                $bj['hospitalName'] = $hospital['name'];
                $res[] = $bj;
            }
        }
		$this->success('',array(
			'total'=>$total,
			'lists'=>$res
		));
    }
    public function checkcoupon(){
        $couponCode = input('code','');
        $hospitalid = input('hospitalId','');
        if(empty($hospitalid) || empty($couponCode)){
            $this->error('参数有误');
            return false;
        }
        $coupon = $this->UseCouponModel->where(['code'=>$couponCode])->field('hospitalid,status')->find();
        if(empty($coupon)){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'核销码有误，请确认'
            ));
            return false;
        }
        if($coupon->hospitalid != $hospitalid){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'优惠券不属于当前医院，请核实后使用'
            ));
        }else if ($coupon->status == 2){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'优惠券已核销，请勿重复提交'
            ));
        }else{
            $this->success('成功',array(
                'code'=>200,
                'data'=>[],
                'msg'=>''
            ));
        }
    }
    public function hexiao(){
        $amount = input('amount','');
        $couponCode = input('couponCode','');
        $hospitalid = input('hospitalId','');
        if(empty($amount)){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'核销金额有误'
            ));
            return false;
        }
        if(empty($hospitalid) || empty($couponCode)){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'参数有误'
            ));
            return false;
        }
        $coupon = $this->UseCouponModel->where(['code'=>$couponCode])->field('hospitalid,status')->find();
        if(empty($coupon)){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'核销码有误，请确认'
            ));
            return false;
        }
        if($coupon->hospitalid != $hospitalid){
            $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'优惠券不属于当前医院，请核实后使用'
            ));
            return false;
        }
        if ($coupon->status == 2){

             $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'优惠券已核销，请勿重复操作'
            ));
            return false;
        }
        $res = $this->UseCouponModel->where(['code'=>$couponCode])->update(array(
            'amount'    => $amount,
            'status'=>2,
            'updatetime'=>time(),
            'hexiaotime'=>time()
        ));
        if($res){
            $this->success('成功',array(
                'code'=>200,
                'data'=>$res,
                'msg'=>''
            ));
        }else{
             $this->success('成功',array(
                'code'=>400,
                'data'=>[],
                'msg'=>'核销失败，请重试'
            ));
             return  false;
        }
    }
}
